package com.fjs.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fjs.pojo.Account;
import com.fjs.pojo.IPAddress;
import com.fjs.pojo.LoginRecord;
import com.fjs.service.AccountService;
import com.fjs.service.LoginRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Title: accountController
 * @Description:
 * @PACKAGE_NAME：com.fjs.internetsystem.controller
 * @Author: 94358 fangjinsen
 * CreateDate: 2022/5/19 21:18
 */
@Controller
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private Account account;

    @Autowired
    private IPAddress ipAddress;

    @Autowired
    private LoginRecord loginRecord;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoginRecordService loginRecordService;


    /**
     * 用户管理界面相关数据获取（admin.html）
     *
     * @return
     */
    @RequestMapping("/queryAccount")
    @ResponseBody
    public String queryAccount() {
        //通过获取登录ID判断是否为管理员，如普通用户调用接口直接返回空
        // 获取当前会话账号id, 如果未登录，则返回null
        Object loginIdDefaultNull = StpUtil.getLoginIdDefaultNull();
        System.out.println("获取到的ID为:" + loginIdDefaultNull);
        //账号为空执行以下操作
        if (loginIdDefaultNull == null) {
            return "未登录账号-拒绝访问";
        }
        //获取登录的ID
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        account.setId(loginIdAsInt);
        List<Account> accounts1 = accountService.accountLogin(account);
        //根据已经登录的ID判断是否为管理员,超级管理员0，普通管理员1，用户标识为2
        boolean spuerAdmin = accounts1.get(0).getIdentity().equals(0);
        boolean admin = accounts1.get(0).getIdentity().equals(1);
        if (spuerAdmin == false && admin == false) {
            System.out.println("未经授权的访问");
            return "未经授权的访问";
        }
        List<Account> accounts = accountService.queryAccount(null);
        System.out.println("当前会话是否登录：" + StpUtil.isLogin());
        return JSON.toJSONString(accounts);
    }

    /**
     * login
     *系统登录接口实现
     * @param account
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestBody Account account) {
        if (StpUtil.getLoginIdDefaultNull() != null) {
            System.out.println("用户已经登录");
            return "already\n" +
                    "\n" +
                    "Sign in";
        }
        System.out.println(account);
        List<Account> accounts = accountService.accountLogin(account);
        //查询结果集为0证明用户名不存在
        if (accounts.size() == 0) {
            return "用户名或者密码错误";
        }
        //查询到存在用户名，进行如下判断，取集合中第一条元素中的密码与前端密码参数进行比对，如布尔值为false表示密码与用户名不匹配
        boolean b = accounts.get(0).getPassWord().equals(account.getPassWord());
        if (b == false) {
            return "用户名或者密码错误";
        }
        //用户密码校验成功执行以下操作
        List<Account> loginQueryAccount = accountService.accountLogin(account);
        //设置id、登录状态参数
        account.setId(loginQueryAccount.get(0).getId());
        //设置用户在线情况,1为在线，0为离线
        account.setLoginFeedBack(1);
        //执行在线情况变更操作，如果受影响的行为0则证明变更失败
        int i = accountService.changeLoginFeedBack(account);
        if (i == 0) {
            return "更改在线情况发生错误";
        }
        //执行完上述操作后将用户ID存入Sa-token，启动服务端会话跟踪
        StpUtil.login(loginQueryAccount.get(0).getId());
        System.out.println("当前会话是否登录：" + StpUtil.isLogin());

        //发送http请求，转化为string类型，调用JSONobject再转化为实体类
        String forObject = restTemplate.getForObject("http://pv.sohu.com/cityjson?ie=utf-8", String.class);
        JSONObject parse = (JSONObject) JSONObject.parse(forObject.substring(18,forObject.length()-1));
        IPAddress ipAddress = new IPAddress(parse.getString("cip"), parse.getString("cid"), parse.getString("cname"));

        //获取系统当前时间
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        String format = dtf.format(now);

        //登录时注入相关属性记录调用新增记录方法
        loginRecord.setUserName(loginQueryAccount.get(0).getUserName());
        loginRecord.setLoginTime(format);
        loginRecord.setLoginAdd(ipAddress.getCname());
        loginRecord.setIpAdd(ipAddress.getCip());
        int i1 = loginRecordService.insertLR(loginRecord);
        if (i1 > 0) {
            System.out.println("新增登录记录成功");
        }
        //得到用户身份并判断
        Integer identity = loginQueryAccount.get(0).getIdentity();
        //超级管理员
        if (identity == 0) {
            return "Super administrator";
        }
        //普通管理员
        if (identity == 1) {
            return "General administrator";
        }
        //普通用户
        if (identity == 2) {
            return "General user";
        }
        return "success";
    }

    /**
     * 退出账号
     *
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public String logout() {
        // 获取当前会话账号id, 如果未登录，则返回null
        Object loginIdDefaultNull = StpUtil.getLoginIdDefaultNull();
        System.out.println("获取到的ID为:" + loginIdDefaultNull);
        //账号为空执行以下操作
        if (loginIdDefaultNull == null) {
            return "未登录账号-拒绝访问";
        }
        //获取登录的ID
        int loginIdAsInt = StpUtil.getLoginIdAsInt();
        account.setId(loginIdAsInt);
        account.setLoginFeedBack(0);
        int i = accountService.changeLoginFeedBack(account);
        StpUtil.logout();
        return "账号ID:" + loginIdAsInt + "已经退出";
    }

    /**
     * 更新信息
     *
     * @param account
     * @return
     */
    @RequestMapping("/updataAccount")
    @ResponseBody
    public String updataAccount(Account account) {
        return null;
    }

    /**
     * 删除用户信息
     *
     * @param account
     * @return
     */
    @RequestMapping("/deleteAccount")
    @ResponseBody
    public String deleteAccount(Account account) {
        return null;
    }
}
